package cn.lizemin.fakedata.security;

import cn.lizemin.fakedata.common.BusinessException;
import cn.lizemin.fakedata.common.ResultEnum;
import cn.lizemin.fakedata.security.entity.Role;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lzm
 * @Date 2024/7/7
 * @description
 */
@Service
public class UserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) {
        // 根据用户名查询用户信息
        User user = getUserByUsername(username);
        // 从数据库中查询出用户的角色
        List<Role> roles = getRolesByUid(user.getId());
        user.setRoles(roles);
        return user;
    }

    private List<Role> getRolesByUid(Integer uid) {
        if (uid == 22) {
            Role role = new Role();
            role.setId(22);
            role.setName("admin");
            role.setZhName("管理员");
            return Lists.newArrayList(role);
        }
        if (uid == 12) {
            Role role = new Role();
            role.setId(12);
            role.setName("root");
            role.setZhName("超级管理员");
            return Lists.newArrayList(role);
        }
        return null;
    }

    private User getUserByUsername(String username) {
        if ("admin".equals(username)) {
            User user = new User();
            user.setId(22);
            user.setUsername("admin");
            user.setPassword("123123");
            return user;
        }

        if ("root".equals(username)) {
            User user = new User();
            user.setId(12);
            user.setUsername("root");
            user.setPassword("123123");
            return user;
        }
        throw new BusinessException(ResultEnum.USER_NOT_EXITS);
    }


}
